<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2020/10/21
 * Time: 10:35
 */

namespace app\api\controller;


use language\Languagemsg;
use think\Db;

class Myyue extends Base
{
    private $user_id; // 用户ID
    private $page; // 页码
    private $create_time;
    
    /**
     * 异地登录验证
     * @return string
     */
    public function __construct()
    {
        $this->msg_language = new Languagemsg();
        $this->language = input('language') ? input('language') : 0;
        $this->user_id = input('user_id');
        $this->page = input('page') ? input('page') : 1;
        $this->create_time = date('Y-m-d H:i:s');
        $time = input('time');
        $value = input('value');
        $reqKey = input('reqKey');
        $auth = $this->checkAll($this->user_id, $time, $value, $reqKey);
        if($auth == 112){
            echo json_encode(['status'=>301, 'msg'=>$this->msg_language->otherLogin[$this->language]]);
            exit;
        }elseif($auth == 2111){
            echo json_encode(['status' => 303, 'msg' => $this->msg_language->frost[$this->language]]);
            exit;
        }
    }
    
    /**
     * 发布约稿
     * @return \think\response\Json
     * yue_title        标题
     * yue_start_time   开始日期
     * yue_end_time     结束日期
     * yue_price        价格
     * yue_explain      要求
     * yue_images       图片
     * yue_painter      画师ID 逗号隔开
     */
    public function addYue(){
        $yue_title = input('yue_title');
        $yue_start_time = input('yue_start_time');
        $yue_end_time = input('yue_end_time');
        $yue_price = input('yue_price');
        $yue_explain = input('yue_explain');
        $yue_images = input('yue_images');
        $yue_painter = input('yue_painter');
        $yue_day_num = $this->getDays($yue_start_time, $yue_end_time);
        $insert = [
            'yue_title' => $yue_title,
            'yue_user_id' => $this->user_id,
            'yue_start_time' => $yue_start_time,
            'yue_end_time' => $yue_end_time,
            'yue_day_num' => $yue_day_num,
            'yue_price' => $yue_price,
            'yue_explain' => $yue_explain,
            'yue_images' => $yue_images,
            'yue_painter' => $yue_painter,
            'yue_time' => $this->create_time,
            'yue_date' => date('Y-m-d')
        ];
        Db::startTrans();
        try{
            // 约稿表
            $yue_id = Db::table('up_yue')->insertGetId($insert);
            if(isset($yue_painter) && $yue_painter != ''){
                // 消息表
                $notice = [
                    'notice_title' => '有一个约稿正在应征画师',
                    'notice_user' => ',' . $yue_painter . ',',
                    'notice_type' => 3,
                    'notice_yue_id' => $yue_id,
                    'notice_read_user' => ',0,',
                    'notice_del_user' => ',0,',
                    'notice_time' => $this->create_time
                ];
                Db::table('up_notice')->insert($notice);
            }
            Db::commit();
//            return json(['status' => 200, 'msg' => '发布成功']);
            return json(['status' => 200, 'msg' => $this->msg_language->publishSuccess[$this->language]]);
        }catch(\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 邀请画师列表
     * @return \think\response\Json
     */
    public function painterList(){
        // 我关注的画师
        $my_attent = Db::table('up_my_attent')
            ->join('up_u_user', 'user_id = att_other_user_id', 'LEFT')
            ->where('att_my_user_id', $this->user_id)
            ->where('user_status', 1)
            ->where('user_role', 'NEQ', 1)
            ->field('user_id, user_username, user_image')
            ->select();
        // 画师
        $painter = Db::table('up_u_user')
            ->where('user_status', 1)
            ->where('user_role', 'IN', '2,3')
            ->where('user_id', '<>', $this->user_id)
            ->field('user_id, user_username, user_image')
            ->select();
        // 高级画师
        $high_painter = Db::table('up_u_user')
            ->where('user_status', 1)
            ->where('user_role', 'IN', '4,5,6')
            ->where('user_id', '<>', $this->user_id)
            ->field('user_id, user_username, user_image')
            ->select();
        $data = [];
        if($my_attent){
            $data['my_attent'] = $my_attent;
        }else{
            $data['my_attent'] = [];
        }
        if($painter){
            $data['painter'] = $painter;
        }else{
            $data['painter'] = [];
        }
        if($high_painter){
            $data['high_painter'] = $high_painter;
        }else{
            $data['high_painter'] = [];
        }
        return json(['status' => 200, 'msg' => $data]);
    }
    
    /**
     * 我发布的约稿列表
     * @return \think\response\Json
     * page    页码
     */
    public function publishYueList(){
        $where['yue_user_id'] = $this->user_id;
        $where['yue_status'] = 1; // 应征中的
//        $where['yue_is_call'] = 1; // 没有画师应征的
        $where['yue_stat'] = 1;
        $list = Db::table('up_yue')
            ->field('yue_id, yue_title, yue_status, yue_day_num, yue_price, yue_date')
            ->where($where)
            ->order('yue_date desc')
            ->page($this->page, 15)
            ->select();
        if($list){
            return json(['status' => 200, 'msg' => $list]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 约稿详情
     * @return \think\response\Json
     * yue_id    约稿ID
     */
    public function showYue(){
        header("Access-Control-Allow-Origin: *");
        $yue_id = input('yue_id');
        $yue = Db::table('up_yue')
            ->join('up_u_user', 'user_id = yue_user_id', 'LEFT')
            ->where('yue_id', $yue_id)
            ->field('yue_title, yue_status, yue_day_num, yue_price, yue_explain, yue_images, yue_date, 
            user_username, user_image, yue_is_call, yue_is_choose, yue_user_id')
            ->find();
        $painter = Db::table('up_yue_join_user')
            ->join('up_u_user', 'user_id = yju_user_id', 'LEFT')
            ->where('yju_yue_id', $yue_id)
            ->where('user_status', 1)
            ->where('yju_status', 1)
            ->field('user_id, user_image')
            ->order('yju_time desc')
            ->select();
        if($painter){
            $join_user = array_column($painter, 'user_id');
            if(in_array($this->user_id, $join_user)){
                $yue['is_join'] = 1; // 我已经应征
            }else{
                $yue['is_join'] = 2; // 我没有参加应征
            }
            $yue['painter'] = $painter;
        }else{
            $yue['painter'] = [];
            $yue['is_join'] = 2;
        }
        if($yue['yue_user_id'] == $this->user_id){
            $yue['is_my'] = 1;
        }else{
            $yue['is_my'] = 2;
        }
        return json(['status' => 200, 'msg' => $yue]);
    }
    
    /**
     * 选择画师
     * @return \think\response\Json
     * yue_id     约稿ID
     * painter_id   画师ID
     */
    public function choosePainter(){
        $yue_id = input('yue_id');
        $painter_id = input('painter_id');
        // 插入订单表、更新约稿状态、更新应征者状态
        $order_num = date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);
        $yue = Db::table('up_yue')->where('yue_id', $yue_id)->field('yue_price')->find();
        $address = Db::table('up_user_address')
            ->where('addr_user_id', $this->user_id)
            ->where('addr_is_default', 1)
            ->field('addr_id')
            ->find();
        if(!$address){
//            return json(['status' => 0, 'msg' => '请先设置默认收货地址']);
            return json(['status' => 0, 'msg' => $this->msg_language->setAddress[$this->language]]);
        }
        
        Db::startTrans();
        try{
            // 更新约稿状态
            Db::table('up_yue')->where('yue_id', $yue_id)->update(['yue_status' => 7, 'yue_is_choose' => 2]);
            // 更新应征者状态,被选中的改为已选中，其他的改为落选
            Db::table('up_yue_join_user')
                ->where('yju_user_id', $painter_id)
                ->where('yju_yue_id', $yue_id)
                ->update(['yju_status' => 3, 'yju_commit_time' => $this->create_time]);
            Db::table('up_yue_join_user')
                ->where('yju_user_id', 'NEQ', $painter_id)
                ->where('yju_yue_id', $yue_id)
                ->update(['yju_status' => 2, 'yju_commit_time' => $this->create_time]);
            // 订单表
            $order = [
                'order_number' => $order_num,
                'order_goods_price' => $yue['yue_price'],
                'order_pay_price' => $yue['yue_price'],
                'order_num' => 1,
                'order_buy_user_id' => $this->user_id,
                'order_sail_user_id' => $painter_id,
                'order_type' => 4,
                'order_yue_id' => $yue_id,
                'order_is_coupon' => 2,
                'order_addr_id' => $address['addr_id'],
                'order_create_time' => $this->create_time
            ];
            // 消息表
            $notice = [
                'notice_title' => '您已被应征的约稿选中',
                'notice_user' => ',' . $painter_id . ',',
                'notice_type' => 4,
                'notice_yue_id' => $yue_id,
                'notice_read_user' => ',0,',
                'notice_del_user' => ',0,',
                'notice_time' => $this->create_time
            ];
            Db::table('up_notice')->insert($notice);
            
            $order_id = Db::table('up_goods_order')->insertGetId($order);
            Db::commit();
//            return json(['status' => 200, 'msg' => '选择成功']);
            return json(['status' => 200, 'msg' => $this->msg_language->chooseSuccess[$this->language], 'order_id' => $order_id]);
        }catch(\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 删除约稿-----发布者/买家删除
     * @return \think\response\Json
     * yue_id     约稿ID
     */
    public function delYue(){
        $yue_id = input('yue_id');
        $yue = Db::table('up_yue')->where('yue_id', $yue_id)->field('yue_is_choose')->find();
        if($yue['yue_is_choose'] == 2){
//            return json(['status' => 0, 'msg' => '已选过画师，不可以删除']);
            return json(['status' => 0, 'msg' => $this->msg_language->refuseDel[$this->language]]);
        }
        Db::startTrans();
        try{
            // 修改约稿状态
            Db::table('up_yue')->where('yue_id', $yue_id)->setField('yue_status', 4);
            // 修改所有应征画师状态->落选
            Db::table('up_yue_join_user')->where('yju_yue_id', $yue_id)->setField('yju_status', 2);
            Db::commit();
//            return json(['status' => 200, 'msg' => '删除成功']);
            return json(['status' => 200, 'msg' => $this->msg_language->delSuccess[$this->language]]);
        }catch(\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 编辑约稿----没有画师应征可以编辑
     * @return \think\response\Json
     * yue_title        标题
     * yue_start_time   开始日期
     * yue_end_time     结束日期
     * yue_price        价格
     * yue_explain      要求
     * yue_images       图片
     * yue_painter      画师ID 逗号隔开
     * yue_id           约稿ID
     */
    public function updateYue(){
        $yue_id = input('yue_id');
        $yue_title = input('yue_title');
        $yue_start_time = input('yue_start_time');
        $yue_end_time = input('yue_end_time');
        $yue_price = input('yue_price');
        $yue_explain = input('yue_explain');
        $yue_images = input('yue_images');
        $yue_painter = input('yue_painter');
        $yue = Db::table('up_yue')->where('yue_id', $yue_id)->field('yue_is_call')->find();
//        if($yue['yue_is_call'] == 2) return json(['status' => 0, 'msg' => '已有画师应征，不可以编辑']);
        if($yue['yue_is_call'] == 2) return json(['status' => 0, 'msg' => $this->msg_language->refuseUpdate[$this->language]]);
        $yue_day_num = $this->getDays($yue_start_time, $yue_end_time);
        $update = [
            'yue_title' => $yue_title,
            'yue_user_id' => $this->user_id,
            'yue_start_time' => $yue_start_time,
            'yue_end_time' => $yue_end_time,
            'yue_day_num' => $yue_day_num,
            'yue_price' => $yue_price,
            'yue_explain' => $yue_explain,
            'yue_images' => $yue_images,
            'yue_painter' => $yue_painter,
            'yue_time' => $this->create_time,
            'yue_date' => date('Y-m-d')
        ];
        Db::startTrans();
        try{
            // 约稿表
            Db::table('up_yue')->where('yue_id', $yue_id)->update($update);
            if(isset($yue_painter) && $yue_painter != ''){
                // 消息表
                $notice = [
                    'notice_title' => '有一个约稿正在应征画师',
                    'notice_user' => ',' . $yue_painter . ',',
                    'notice_type' => 3,
                    'notice_yue_id' => $yue_id,
                    'notice_read_user' => ',0,',
                    'notice_del_user' => ',0,',
                    'notice_time' => $this->create_time
                ];
                Db::table('up_notice')->insert($notice);
            }
            Db::commit();
//            return json(['status' => 200, 'msg' => '编辑成功']);
            return json(['status' => 200, 'msg' => $this->msg_language->updateSuccess[$this->language]]);
        }catch(\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 店铺--我参加的应征中和被选中的约稿
     * @return \think\response\Json
     * page   页码
     */
    public function myShopYueList(){
        // 我参加的应征中和被选中的约稿
        $yue = Db::table('up_yue_join_user')
            ->join('up_yue', 'yue_id = yju_yue_id', 'LEFT')
            ->join('up_u_user', 'user_id = yue_user_id', 'LEFT')
            ->where('yju_user_id', $this->user_id)
            ->where('yju_status', 'IN', '1,3')
            ->where('yue_stat', 1)
            ->field('yju_id, yue_id, user_username, user_phone, yue_title, yue_status, yue_day_num, 
            yue_price, yue_date, yju_status')
            ->order('yju_time desc')
            ->page($this->page, 15)
            ->select();
        if($yue){
            foreach($yue as $k => $v){
                if($v['yju_status'] == 3){
                    $order_num = Db::table('up_goods_order')->where('order_yue_id', $v['yue_id'])->value('order_number');
                    $yue[$k]['order_num'] = $order_num;
                }else{
                    $yue[$k]['order_num'] = '';
                }
            }
            return json(['status' => 200, 'msg' => $yue]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 店铺---我参加的落选的和我取消的约稿
     * @return \think\response\Json
     * page    页码
     */
    public function LoseOrCancelList(){
        $yue = Db::table('up_yue_join_user')
            ->join('up_yue', 'yue_id = yju_yue_id', 'LEFT')
            ->join('up_u_user', 'user_id = yue_user_id', 'LEFT')
            ->where('yju_user_id', $this->user_id)
            ->where('yju_status', 'IN', '2,4')
            ->where('yue_stat', 1)
            ->field('yju_id, yue_id, user_username, user_phone, yue_title, yue_day_num, yue_price, 
            yue_date, yju_status')
            ->order('yju_time desc')
            ->page($this->page, 15)
            ->select();
        if($yue){
            return json(['status' => 200, 'msg' => $yue]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 画师主动取消应征中的约稿
     * @return \think\response\Json
     * yju_id     参加约稿的记录ID
     * yue_id     约稿ID
     */
    public function sailCancelYue(){
        /*应征中的约稿，画师自己取消，则画师的参与状态改成已取消，
          并且看看是不是只有这一个画师参加了，如果是，要讲约稿yue_is_call状态改成没有画师应征*/
        $yju_id = input('yju_id');
        $yue_id = input('yue_id');
        Db::startTrans();
        try{
            // 画师参与状态
            Db::table('up_yue_join_user')
                ->where('yju_id', $yju_id)
                ->update([
                    'yju_status' => 4,
                    'yju_cancel_time' => $this->create_time
                ]);
            // 是否有应征中的画师
            $have_painter = Db::table('up_yue_join_user')
                ->where('yju_yue_id', $yue_id)
                ->where('yju_status', 1)
                ->find();
            if(!$have_painter){
                Db::table('up_yue')->where('yue_id', $yue_id)->setField('yue_is_call', 2);
            }
            Db::commit();
//            return json(['status' => 200, 'msg' => '取消成功']);
            return json(['status' => 200, 'msg' => $this->msg_language->cancelSuccess[$this->language]]);
        }catch(\Exception $e){
            Db::rollback();
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 店铺---约稿详情
     * @return \think\response\Json
     * yju_id    应征约稿ID
     */
    public function shopYueDetail(){
//        header("Access-Control-Allow-Origin: *");
        $yju_id = input('yju_id');
        $yue = Db::table('up_yue_join_user')
            ->join('up_yue', 'yju_yue_id = yue_id', 'LEFT')
            ->join('up_goods_order', 'order_yue_id = yue_id', 'LEFT')
            ->join('up_user_address', 'order_addr_id = addr_id', 'LEFT')
            ->join('up_area ua1', 'ua1.district_id = addr_sheng', 'LEFT')
            ->join('up_area ua2', 'ua2.district_id = addr_shi', 'LEFT')
            ->join('up_area ua3', 'ua3.district_id = addr_qu', 'LEFT')
            ->where('yju_id', $yju_id)
            ->field('yju_status, yue_status, addr_id, addr_name, addr_phone, addr_email, ua1.district sheng, 
            ua2.district shi, ua3.district qu, addr_address, yue_title, yue_explain, yue_images, yue_price, 
            yue_day_num, order_id, order_number, yju_time, yue_time, order_send_time, order_over_time, yju_cancel_time, 
            yju_id, yue_id')
            ->find();
        if($yue['yue_images']){
            $images = trim($yue['yue_images'], ',');
            $yue['yue_images'] = explode(',', $images);
        }else{
            $yue['yue_images'] = [];
        }
        return json(['status' => 200, 'msg' => $yue]);
    }
    
    /**
     * 获取两个日期相差的天数
     * @param $begin_date    开始日期
     * @param $end_date      结束日期
     * @return float
     */
    private function getDays($begin_date, $end_date){
        $between = strtotime($end_date) - strtotime($begin_date);
        $days = $between/60/60/24;
        return $days;
    }
}